package com.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.common.Result;
import com.demo.pojo.dto.StudentListDTO;
import com.demo.pojo.entity.Student;
import com.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * 学生控制器
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    /**
     * 分页查询学生列表
     * @param pageNum 当前页
     * @param pageSize 每页大小
     * @param stuNo 学号（-1 或空忽略）
     * @param stuName 姓名（空忽略）
     * @param stuSex 性别（-1 忽略，0 女，1 男）
     * @param stuPhone 手机（空忽略）
     * @return 分页结果
     */
    @GetMapping("/listPage")
    public Result<IPage<StudentListDTO>> getStudentList(
            @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "stuNo", required = false) Long stuNo,
            @RequestParam(name = "stuName", required = false) String stuName,
            @RequestParam(name = "stuSex", required = false) Integer stuSex,
            @RequestParam(name = "stuPhone", required = false) String stuPhone) {
        Page<Student> page = new Page<>(pageNum, pageSize);
        IPage<StudentListDTO> result = studentService.getStudentList(page, stuNo, stuName, stuSex, stuPhone);
        return Result.success(result);
    }
    
    /**
     * 根据ID查询学生
     * @param id 学生ID
     * @return 学生信息
     */
    @GetMapping("/select")
    public Result<Student> getStudentById(@RequestParam Integer id) {
        Student student = studentService.getStudentById(id);
        if (student == null) {
            return Result.error("学生不存在");
        }
        return Result.success(student);
    }
    
    /**
     * 根据学号查询学生
     * @param stuNo 学号
     * @return 学生信息
     */
    @GetMapping("/no/{stuNo}")
    public Result<Student> getStudentByNo(@PathVariable Long stuNo) {
        Student student = studentService.getStudentByNo(stuNo);
        if (student == null) {
            return Result.error("学生不存在");
        }
        return Result.success(student);
    }
    
    /**
     * 添加学生
     * @param student 学生信息
     * @return 操作结果
     */
    @PostMapping("/save")
    public Result<String> addStudent(@RequestBody Student student) {
        try {
            boolean success = studentService.addStudent(student);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新学生信息
     * @param student 学生信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public Result<String> updateStudent(@RequestBody Student student) {
        try {
            boolean success = studentService.updateStudent(student);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除学生
     * @param id 学生ID
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public Result<String> deleteStudent(@RequestParam Integer id) {
        boolean success = studentService.deleteStudent(id);
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }
    
    /**
     * 批量删除学生
     * @param ids 学生ID列表
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    public Result<String> deleteStudents(@RequestBody List<Integer> ids) {
        boolean success = studentService.deleteStudents(ids);
        if (success) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    /**
     * 学生登录：学号 + 身份证后六位
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> body) {
        String stuNoStr = body.get("stuNo");
        String idTail6 = body.get("idTail6");
        Long stuNo = stuNoStr == null || stuNoStr.isEmpty() ? null : Long.valueOf(stuNoStr);
        Student student = studentService.login(stuNo, idTail6);
        Map<String, Object> resp = new HashMap<>();
        resp.put("user", student);
        return Result.success(resp);
    }
}
